use std::collections::HashMap;

struct Solution {}

fn main() {}

impl Solution {
    pub fn count_largest_group(n: i32) -> i32 {
        let mut sum_cnt_map: HashMap<i32, i32> = HashMap::new();
        (1..=n).for_each(|c| { Self::cal_sum_add_cnt(&mut sum_cnt_map, &c); });

        let max = *sum_cnt_map.values().max_by(|x, y| x.cmp(&y)).unwrap();
        sum_cnt_map.values().filter(|&x| *x == max).count() as i32
    }

    fn cal_sum_add_cnt(sum_cnt_map: &mut HashMap<i32, i32>, num: &i32) {
        let s = Self::get_number_sum(num);
        Self::record_cnt(sum_cnt_map, &s);
    }

    fn record_cnt(map: &mut HashMap<i32, i32>, s: &i32) {
        if map.contains_key(&s) {
            let cnt = map.get(&s).unwrap();
            map.insert(*s, cnt + 1);
        } else {
            map.insert(*s, 1);
        }
    }

    fn get_number_sum(n: &i32) -> i32 {
        let n_string = n.to_string();
        let sum: u32 = n_string.as_bytes().iter().map(|&c| { (c as char).to_digit(10).unwrap() }).collect::<Vec<u32>>().into_iter().sum();
        sum as i32
    }
}